package com.itheima.health.service.impl;

import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Order;
import com.itheima.health.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 数据报表service
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private OrderDao orderDao;


    @Override
    public Map<String, Object> getBussinessReport() {
        Map<String, Object> resultMap = new HashMap<>();

        //日期处理
        LocalDate today = LocalDate.now();//  年月日
        //本周第一天
        LocalDate weekFirstDay = today.with(DayOfWeek.MONDAY);
        //本周最后一天
        LocalDate weekLastDay = today.with(DayOfWeek.SUNDAY);
        //本月第一天
        LocalDate monthFirstDay = today.with(TemporalAdjusters.firstDayOfMonth());
        //本月最后一天
        LocalDate monthLastDay = today.with(TemporalAdjusters.lastDayOfMonth());
        //会员数据 memberDao
        //      reportDate -> yyyy-MM-dd        //日期

        resultMap.put("reportDate", today.toString());
        //      todayNewMember -> number		// 今日新增会员
        resultMap.put("todayNewMember", memberDao.countByRegTimeRange(today, today));
        //      thisWeekNewMember -> number		// 本周新增会员
        resultMap.put("thisWeekNewMember", memberDao.countByRegTimeRange(weekFirstDay, weekLastDay));
        //      thisMonthNewMember -> number	// 本月新增会员
        resultMap.put("thisMonthNewMember", memberDao.countByRegTimeRange(monthFirstDay, monthLastDay));
        //      totalMember -> number			//  总会员
        resultMap.put("totalMember", memberDao.countByRegTimeBefore(today));

        //预约数据 orderDao
        //      todayOrderNumber -> number		// 今日预约人数
        resultMap.put("todayOrderNumber", orderDao.countByOrderDateRange(today, today, null));
        //      thisWeekOrderNumber -> number	// 本周预约人数
        resultMap.put("thisWeekOrderNumber", orderDao.countByOrderDateRange(weekFirstDay, weekLastDay, null));
        //      thisMonthOrderNumber -> number	// 本月预约人数
        resultMap.put("thisMonthOrderNumber", orderDao.countByOrderDateRange(monthFirstDay, monthLastDay, null));
        //      todayVisitsNumber -> number		// 今日到诊人数
        resultMap.put("todayVisitsNumber", orderDao.countByOrderDateRange(today, today, Order.ORDERSTATUS_YES));
        //      thisWeekVisitsNumber -> number	// 本周到诊人数
        resultMap.put("thisWeekVisitsNumber", orderDao.countByOrderDateRange(weekFirstDay, weekLastDay, Order.ORDERSTATUS_YES));
        //      thisMonthVisitsNumber -> number	// 本月到诊人数
        resultMap.put("thisMonthVisitsNumber", orderDao.countByOrderDateRange(monthFirstDay, monthLastDay, Order.ORDERSTATUS_YES));
        //热门套餐
        //      hotSetmeals ->  [ {"proportion":0.4545,"name":"粉红珍爱(女)升级TM12项筛查体检套餐","setmeal_count":5}]	// 热门套餐
        resultMap.put("hotSetmeal", orderDao.countByHotSetMeal(4));

        return resultMap;
    }
    /**
     * 导出运营数据报表
     */
    @Override
    public void exportBusinessReport(HttpServletResponse response) {
        //1-获取数据
        Map<String, Object> reportData = getBussinessReport();
        log.debug("[导出运营数据报表]rpc rsp:{}", reportData);
        // 取出返回结果
        String reportDate = (String) reportData.get("reportDate");
        // 获取会员相关数据
        Long todayNewMember = (Long) reportData.get("todayNewMember");
        Long thisWeekNewMember = (Long) reportData.get("thisWeekNewMember");
        Long thisMonthNewMember = (Long) reportData.get("thisMonthNewMember");
        Long totalMember = (Long) reportData.get("totalMember");
        // 获取预约相关数据
        Long todayOrderNumber = (Long) reportData.get("todayOrderNumber");
        Long thisWeekOrderNumber = (Long) reportData.get("thisWeekOrderNumber");
        Long thisMonthOrderNumber = (Long) reportData.get("thisMonthOrderNumber");
        // 获取到诊相关数据
        Long todayVisitsNumber = (Long) reportData.get("todayVisitsNumber");
        Long thisWeekVisitsNumber = (Long) reportData.get("thisWeekVisitsNumber");
        Long thisMonthVisitsNumber = (Long) reportData.get("thisMonthVisitsNumber");
        // 获取套餐数据
        List<Map> hotSetmeal = (List<Map>) reportData.get("hotSetmeal");

        //2-读取模板构造workBook
        try  {
            InputStream is = this.getClass().getClassLoader().getResourceAsStream("report_template.xlsx");
            XSSFWorkbook workbook = new XSSFWorkbook(is);
            OutputStream os = response.getOutputStream();
            Sheet sheet = workbook.getSheetAt(0);
            //3-填入数据
            //日期
            sheet.getRow(2).getCell(5).setCellValue(reportDate);
            //会员统计数据
            sheet.getRow(4).getCell(5).setCellValue(todayNewMember);
            sheet.getRow(4).getCell(7).setCellValue(totalMember);
            sheet.getRow(5).getCell(5).setCellValue(thisWeekNewMember);
            sheet.getRow(5).getCell(7).setCellValue(thisMonthNewMember);
            //预约到诊数据统计
            sheet.getRow(7).getCell(5).setCellValue(todayOrderNumber);
            sheet.getRow(7).getCell(7).setCellValue(todayVisitsNumber);
            sheet.getRow(8).getCell(5).setCellValue(thisWeekOrderNumber);
            sheet.getRow(8).getCell(7).setCellValue(thisWeekVisitsNumber);
            sheet.getRow(9).getCell(5).setCellValue(thisMonthOrderNumber);
            sheet.getRow(9).getCell(7).setCellValue(thisMonthVisitsNumber);
            //热门套餐
            int rowNum = 12;
            for (Map setMeal : hotSetmeal) {
                Row row = sheet.getRow(rowNum);
                row.getCell(4).setCellValue((String) setMeal.get("name"));
                row.getCell(5).setCellValue((Long) setMeal.get("setmeal_count"));
                row.getCell(6).setCellValue(((BigDecimal) setMeal.get("proportion")).doubleValue());
                rowNum++;
            }

            //4-写入网络输出流
            //写入返回流
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition", "attachment;fileName=" + reportDate + "_report.xlsx");
            workbook.write(os);

        } catch (IOException e) {
            log.error("",e);
            throw new BusinessRuntimeException(MessageConst.ACTION_FAIL);
        }
    }
}
